import axios from 'axios'
const instance = axios.create({
    baseURL: '',
})

// 错误处理函数
const err = (error) => {
    if (error.response) {
        console.log(error)
    }
    return Promise.reject(error)
}


// request interceptor(请求拦截器)
instance.interceptors.request.use(config => {
    const token = localStorage.getItem("token")
    if (token) {
        config.headers['Authorization'] = " Bearer " + token // 让每个请求携带自定义 token 请根据实际情况自行修改
    }
    return config
}, err)


// response interceptor（接收拦截器）
instance.interceptors.response.use((response) => {
    const res = response.data
    if (response.status == 200 && (res.status == 1 || res.access_token)) {
        return Promise.resolve(res)
    } else {
        debugger
        return Promise.reject(res)
    }
}, err)

export const Post = (api, res) => {
    return instance({
        url: api,
        method: 'POST',
        data: res
    })
}

export const Get = (api, res) => {
    return instance({
        url: api,
        method: 'GET',
        data: res
    })
}

export const Put = (api, res) => {
    return instance({
        url: api,
        method: 'PUT',
        data: res
    })
}

export const Delete = (api, res) => {
    return instance({
        url: api,
        method: 'DELETE',
        data: res
    })
}

export default {
    instance,
    Post,
    Put,
    Get,
    Delete,
};